import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/networks/business/models/business_response.dart';
import 'package:edu/utils/data_fetcher.dart';

class CourseReviewPageLogic extends ChangeNotifier {
  final int courseId;
  final int rating;
  final String? reviewContent;

  late final TextEditingController controller;
  late final FocusNode focusNode;

  late int newRating = rating;

  CourseReviewPageLogic({
    required this.courseId,
    required this.rating,
    this.reviewContent,
  });

  void init() {
    controller = TextEditingController();
    focusNode = FocusNode();

    controller.text = reviewContent ?? '';
  }

  Future<CourseReview?> review() async {
    final newReview = controller.text.trim();
    if (newReview.isEmpty) {
      EasyLoading.showError(AppStrings.contentCannotBeEmpty);
      return null;
    }

    if (newReview == reviewContent && newRating == rating) {
      return null;
    }

    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.clear,
        dismissOnTap: false,
      );
      final response = await DataFetcher.shared.businessApi.reviewCourse(
        courseId,
        newRating,
        newReview,
      );
      EasyLoading.dismiss();
      if (response.code == 0) {
        EasyLoading.showSuccess(AppStrings.reviewSuccess);
        final newReview = response.review!;
        return newReview;
      } else {
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
        return null;
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      log('Error: $e');
      return null;
    }
  }
}
